<template>
    <el-form ref="ruleFormRef" :rules="rules" :model="formBanner" label-width="80px">
        <el-row>

            <el-col :span="6">
      <el-form-item label="轮播图名称" prop="bannerName">
        <el-input v-model="formBanner.bannerName" placeholder="请输入轮播图名称"/>
      </el-form-item>
    </el-col>
            <el-col :span="24">
                <el-form-item label="轮播图封面" prop="bannerImg">
                    <!--上传图片控件 start-->
                    <el-upload :action="uploadURL" name="fileResource" list-type="picture-card" :auto-upload="true"
                        :limit="1" :on-success="handleSuccess">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <!--上传图片控件 end-->
                </el-form-item>
            </el-col>


        </el-row>
    </el-form>
    <div class="dialog-button-wrap">
        <el-button @click="close">取消</el-button>
        <el-button @click="addBanner(ruleFormRef)" type="success" :loading="subLoading" color="#083a6d">保存</el-button>
    </div>
</template>
    
<script setup lang="ts">
import { ref, reactive, } from 'vue'
import { addBannerApi } from "@/api/edu/banner/banner"
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import '@wangeditor/editor/dist/css/style.css' // 引入 css

// 表单实例对象
const ruleFormRef = ref<FormInstance>()
// 表单约束规则对象
const rules = reactive<FormRules>({
    bannerImg: [{ required: true, message: '封面不能为空', trigger: 'blur' }],
    bannerName: [{ required: true,message: '轮播图名称不能为空',trigger: 'blur' }],

})
// 定义事件
const emit = defineEmits(['closeAddBannerForm', 'success'])
// 按钮状态
const subLoading = ref(false)
// 表单数据对象
const formBanner = reactive({
    bannerName: '',
    bannerImg: ''
})
// 新增轮播图信息
const addBanner = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        subLoading.value = true
        if (valid) {
            const { data } = await addBannerApi(formBanner)
            if (data.status === 200) {
                ElMessage.success(data.message)
                emit('success')
            } else {
                ElMessage.error(data.message)
            }
        } else {
            ElMessage.error('提交失败，你还有未填写的项！')
        }
    })
    subLoading.value = false
}


// 服务器路径
const url = import.meta.env.VITE_APP_BASE_API
// 图片上传到服务器路径
const uploadURL = url + "user/userIcon"
// 上传成功回调函数
const handleSuccess = (response: any, uploadFile: UploadFile) => {
    formBanner.bannerImg = response.result.userIcon
}

// 取消表单
const close = () => {
    emit('closeAddBannerForm')
}
// onMounted(() => {
  
// })
</script>
    
<style scoped>
.dialog-button-wrap {
    text-align: center;
    margin-top: 20px;
}
</style>
    